package org.blogwu.learn.netty学习.chapter0.bio2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            System.out.println("服务器启动了！");
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("有客户端连接了：" + socket.getInetAddress().getHostAddress() + ";port:" + socket.getPort());
                new Thread(() -> {
                    try (
                            InputStream inputStream = socket.getInputStream();
                            OutputStream outputStream = socket.getOutputStream();
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
                    ) {
                        String data = null;
                        while ((data = bufferedReader.readLine()) != null) {
                            System.out.println("从客户端取到的数据：" + data);
                            bufferedWriter.write("数据已收到，数据长度为：" + data.length());
                            bufferedWriter.newLine();
                            bufferedWriter.flush();
                        }
                        System.out.println("客户端连接断开");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
                // cnm  记得start
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
